package com.project651.www;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import com.project651.www.StartGameService.StartGameServiceBinder;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class StartGame extends Activity implements OnClickListener {
	EditText wordField;
	TextView wordSelect;
	TextView ipAddress;
	Intent intentServerService;
	boolean startGameBound = false;
	StatusNotifier statusNotifier;
	Button submitWord;
	
	private StartGameService startGameService;
	
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.startgame);
	        
	        submitWord = (Button) findViewById(R.id.submitword);
	        submitWord.setOnClickListener(this);
	        submitWord.setText("Submit");
	        
	        wordField = (EditText) findViewById(R.id.wordfield);
	        wordSelect = (TextView) findViewById(R.id.selectword);
	        ipAddress = (TextView) findViewById(R.id.ipaddress);
	        
	        String address = getLocalIpAddress();
	        if(address == null) ipAddress.setText("No address");
	        else ipAddress.setText(address);
	        wordSelect.setText("Select Word:");
	        
	        // create notifier
	        registerReceiver(new StatusNotifier(), new IntentFilter(StartGameService.SERVER));
	        
	        // start server process
	        intentServerService = new Intent(this, StartGameService.class);
	        bindService(intentServerService, startGameConnection, Context.BIND_AUTO_CREATE);
	        startService(intentServerService);
	 }
	 
	 public String getLocalIpAddress() {
		    try {
		        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
		            NetworkInterface intf = en.nextElement();
		            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
		                InetAddress inetAddress = enumIpAddr.nextElement();
		                if (!inetAddress.isLoopbackAddress()) {
		                    return inetAddress.getHostAddress().toString();
		                }
		            }
		        }
		    } catch (SocketException ex) {
		        //Log.e(LOG_TAG, ex.toString());
		    }
		    return null;
		}
	 
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.submitword:
			CharSequence word = wordField.getText();
			if (word.length() < 3 || word.length() > 12) {
				//TODO error message for bad word
			} else if(!word.toString().matches("^[a-zA-z]+$")){
				//there are invalid characters
				//TODO error message for bad word
			} else {
				//valid word, so start a game
				Bundle b = new Bundle();
				b.putCharSequence("secretWord", word.toString().toUpperCase());
				startGameService.sendWord(word);
				/*
				Intent i = new Intent(this, JoinGameKeyboard.class);
				i.putExtras(b);
				startActivity(i);
				*/
				wordField.setText("");
			}
			break;
		}
		
	}
	
	private ServiceConnection startGameConnection = new ServiceConnection() {

		public void onServiceDisconnected(ComponentName name) {
			startGameBound = false;
		}

		public void onServiceConnected(ComponentName name, IBinder service) {
			StartGameServiceBinder binder = (StartGameServiceBinder) service;
			startGameService = binder.getService();
			startGameBound = true;
			((TextView) findViewById(R.id.servicebound)).setText("Service is bound.");
		}
	};
	
	private class StatusNotifier extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle bundle = intent.getExtras();
			((TextView) findViewById(R.id.connection)).setText("Connection established");

			int status = 0;
			// on receiving a command
			if (status == 1) {
				//you win!
			} else {
				//you lose!
			}
		}
	}

}
